﻿using FSM.IBll;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FSM.Web.Models.Fileter
{
    /// <summary>
    /// 操作权限认证
    /// </summary>
    public class OperateAuthorizeAttribute : TypeFilterAttribute
    {
        #region 字段

        /// <summary>
        /// 模块
        /// </summary>
        private string _module;

        /// <summary>
        /// 动作
        /// </summary>
        private string _action;

        #endregion

        public OperateAuthorizeAttribute(string module, string action) : base(typeof(OperateAuthrize))
        {
            _module = module;
            _action = action;
            this.Arguments = new object[] { _module, _action};
        }

        class OperateAuthrize : IAuthorizationFilter
        {
            #region 字段

            /// <summary>
            /// 模块
            /// </summary>
            private string _module;

            /// <summary>
            /// 动作
            /// </summary>
            private string _action;

            #endregion

            #region 构造函数

            public OperateAuthrize(string module, string action)
            {
                this._module = module;
                this._action = action;
            }

            #endregion

            public void OnAuthorization(AuthorizationFilterContext context)
            {
                if (string.IsNullOrEmpty(_module))
                {
                    var desc = context.ActionDescriptor as ControllerActionDescriptor;
                    if (desc.Properties.ContainsKey("ModuleKey"))
                    {
                        var obj = desc.Properties["ModuleKey"];
                    }
                }
                string userNo = AuthencationHelper.GetLoginUserNo(context.HttpContext.User);
                var _bll = (ISysSettingBll)context.HttpContext.RequestServices.GetService(typeof(ISysSettingBll));
                bool hasPower = _bll.HasOperationPower(userNo, _module, _action);
                if (hasPower == false)
                {
                    context.Result = new JsonResult(new DataResultModel
                    {
                        success = false,
                        message = "没有此操作的权限"
                    });
                }
            }
        }
    }
}
